# file:: entity.rb
# author::  Ralph M. Churchill
# version::
# date::
#
# This source code copyright (C) 2006 by Ralph M. Churchill
# All rights reserved.
#
# Released under the terms of the GNU General Public License
# See LICENSE file for additional information.

class Module
    def properties(*sym)
        sym.each do |s|
            class_eval <<-EOC
                def #{s}
                    @props ||= {}
                    @props[:#{s}]
                end
                def #{s}=(val)
                    @props ||= {}
                    @props[:#{s}] = val
                end
            EOC
            class_eval <<-EOC
                def to_yaml_properties
                    ['@props']
                end
            EOC
        end
    end
end

module Nameable
    def named?(name)
        return false unless self.respond_to?(:name)
		myname = self.name.downcase
		name.strip!
		name.downcase!
		# full match
		return true if myname == name
		# partial match
		# hrm # return true if name.empty?
		# matches if any of the words START with a match
		if myname.index(name) then
			myname.split(' ').each do |word|
				return true if word.index(name)==0
			end
		end
		false
    end
end

class Entity
    include Comparable, Nameable
    properties :oid,:name,:description

    def <=>(e)
        self.oid<=>e.oid
    end
    def to_s
        self.name
    end
    def clone
        # deep copy ONLY THE PROPERTIES
        newobj = Marshal.load(Marshal.dump(self))
        newobj.instance_variable_get(:@props)[:oid] = nil
        newobj
    end
    def dup
        clone
    end

    def self.metaclass
        class << self
            self
        end
    end
    def self.uses_templates_from(template_db)
        class_eval <<-EOC
            def template=(t)
                raise "Not a valid template!" unless t.respond_to?(:oid)
                @props ||= {}
                @props[:template_id] = t.oid
            end
            def template
                @props ||= {}
                #{template_db}.instance.get_template(@props[:template_id])
            end
        EOC
    end
end    
